<?php
class Lib_Builder
{
	
	protected $options;
	
	protected $schema;
		
	protected $forms = array();
	
	
	/**
    * Constructor
    * ..
    */	
	public function __construct(){
		$this->options = new lib_Options();
	}
	
	/**
    * loadSchema
    * Creates an schema object from the yml file.
    */	
	public function setSchema($yml){
		$this->schema = $yml;
	}
	
	/**
    * setOption
    * set a option.
    */	
	public function setOption($name, $value){
		if($this->options != ''){
			$this->options->setOption($name, $value);
		}
	}
	
	/**
    * getParser
    * Creates the right parser for the form objects.
    */
	protected function getParser(){
		$parser = $this->options->getOption('parser');
		
		switch ($parser) {
			case 'Zend':
				return new Zend_Form();
				break;
			case 'CakePHP':
				return new CakePHP_Form();
				break;
			case 'Plain':
				return new Plain_Form();
				break;
		}
	}
	
	/**
    * BuildForms
    * Builds seperated form objects
    */	
	public function BuildForms(){
		foreach($this->schema as $name => $formSchema){
			$form = $this->getParser();
			$form->setSchema($name, $formSchema);
			$form->build();
			$this->forms[$name] = $form;
		}
	}
	
	/**
    * BuildAll (Complex function!)
    * Writes all forms with included elements to a file and base file.
    */	
	public function BuildAll(){
		$this->BuildForms();
	
		foreach($this->forms as $form){
			$dir = $this->options->getOption('targetPath');
			$name = $form->getOption('name');
			if(!file_exists($dir)){
				mkdir($dir);
			} 
		
			//Writes Base file
			if($this->options->getOption('generateFormClasses')){
				$path_c = $dir.'/'.$this->options->getOption('baseClassesDirectory').'/Base'.$name.'.php';
				
				//Start writer
				$data = $form->getBaseForm();
			
				$fc = fopen($path_c, 'w');
				fwrite($fc, $data);
				fclose($fc);
			}
			
			//Writes form file
			if($this->options->getOption('generateFormClasses')){
				$path_f = $dir.'/'.$name.'.php';
				
				if(!file_exists($path_f)){
					//Start writer
					$data = $form->getForm();
				
					$ff = fopen($path_f, 'w');
					fwrite($ff, $data);
					fclose($ff);
				}
			}
			
			
		
		}
	}
	
	
	
}
?>